package com.umeox.zikrringtest.single_test

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.umeox.base.BaseRecyclerViewAdapter
import com.umeox.base.BaseViewHolder
import com.umeox.sdk_ring.RingScanCallback
import com.umeox.sdk_ring.UMScanResult
import com.umeox.sdk_ring.scan.RingScanner
import com.umeox.zikrringtest.*
import com.umeox.zikrringtest.single_test.gsensor.SensorTestActivity

class SearchActivity : AppCompatActivity(),
    com.umeox.base.BaseRecyclerViewAdapter.OnItemClickListener<DeviceInfo>, RingScanCallback,
    AdapterView.OnItemSelectedListener {

    private val macAddressList = mutableListOf<String>()
    private val allDeviceList = mutableListOf<DeviceInfo>()
    private val targetDeviceList = mutableListOf<DeviceInfo>()

    private val scannerManager = RingScanner(this, this, Handler(Looper.getMainLooper()))

    private val adapter = DeviceListAdapter()

    private lateinit var zikrArray: List<String>

    private var filterTarget = "Zikr.*,SC01.*"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_base_search)

        zikrArray = resources.getStringArray(R.array.zikr).toList()

        findViewById<Button>(R.id.bt_rescan).setOnClickListener {
            requestPermissionCompat()
        }

        findViewById<RecyclerView>(R.id.rv_device_list).adapter = adapter
        adapter.setOnItemClickListener(this)

        findViewById<Spinner>(R.id.spinner).onItemSelectedListener = this

        requestPermissionCompat()
    }

    override fun onItemClick(view: View?, position: Int, t: DeviceInfo) {
        if (intent.getIntExtra("type", 1) == 2) {
            startActivity(Intent(this, SensorTestActivity::class.java).apply {
                putExtra("macAddress", t.macAddress)
            })
        } else {
            startActivity(Intent(this, SingleTestActivity::class.java).apply {
                putExtra("macAddress", t.macAddress)
            })
        }
    }

    private fun requestPermissionCompat() {
        requestInner()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun requestInner() {
        //检查蓝牙开关
        if (!getBluetoothStatus()) {
            Toast.makeText(this, "请开打蓝牙开关后再试", Toast.LENGTH_SHORT).show()
            setBluetoothStatus(true)
            return
        }

        //检查GPS状态
        if (!getGPSStatus()) {
            Toast.makeText(this, "请开打GPS开关后再试", Toast.LENGTH_SHORT).show()
            return
        }

        macAddressList.clear()
        allDeviceList.clear()
        adapter.notifyDataSetChanged()
        scannerManager.stopScan()
        scannerManager.startScan()
    }

    @SuppressLint("MissingPermission")
    override fun onScanResult(result: UMScanResult) {
        val regexList = "Zikr.*,SC01.*".split(",")
        for (regex in regexList) {
            val regex = Regex(regex)
            if (!TextUtils.isEmpty(result.device.name) && (result.device.name.matches(regex))) {
                if (!macAddressList.contains(result.device.address)) {
                    macAddressList.add(result.device.address)
                    allDeviceList.add(
                        DeviceInfo(
                            result.device.name,
                            result.rssi,
                            result.device.address
                        )
                    )
                    updateData()
                }
            }
        }
    }

    override fun onPause() {
        super.onPause()
        scannerManager.stopScan()
    }

    @SuppressLint("NotifyDataSetChanged")
    fun updateData() {
        if (filterTarget == "Zikr.*,SC01.*") {
            targetDeviceList.clear()
            targetDeviceList.addAll(allDeviceList)
            targetDeviceList.sortBy {
                it.rssi
            }
            targetDeviceList.reverse()
            adapter.list.clear()
            adapter.list.addAll(targetDeviceList)
            adapter.notifyDataSetChanged()
        } else {
            targetDeviceList.clear()
            for (deviceInfo in allDeviceList) {
                if (deviceInfo.deviceName == filterTarget) {
                    targetDeviceList.add(deviceInfo)
                }
            }

            targetDeviceList.sortBy {
                it.rssi
            }
            targetDeviceList.reverse()
            adapter.list.clear()
            adapter.list.addAll(targetDeviceList)
            adapter.notifyDataSetChanged()
        }
    }

    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        filterTarget = if (position == 0) {
            "Zikr.*,SC01.*"
        } else {
            zikrArray[position]
        }

        updateData()
    }

    override fun onNothingSelected(parent: AdapterView<*>?) {
    }
}

class DeviceListAdapter(var list: MutableList<DeviceInfo> = mutableListOf()) :
    com.umeox.base.BaseRecyclerViewAdapter<DeviceInfo>() {
    override fun getLayoutId(viewType: Int): Int = R.layout.item_device

    override fun getDataByPosition(position: Int): DeviceInfo = list[position]

    override fun getTotalSize(): Int = list.size

    @SuppressLint("SetTextI18n")
    override fun convert(holder: com.umeox.base.BaseViewHolder, data: DeviceInfo, position: Int) {
        holder.getView<TextView>(R.id.item_name).text = "${data.deviceName}-${data.rssi}"
        holder.getView<TextView>(R.id.item_mac).text = data.macAddress
    }
}